//
//  AppDelegate.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/5/2.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "AppDelegate.h"
#import "UserModel.h"
#import "HomePageViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#import "IFlyMSC/IFlyMSC.h" // 讯飞 语音识别
#import "WZXLaunchViewController.h"// 广告
#import "HomeWebViewController.h"// 广告详情 如果有可以放开
#import <UMSocialCore/UMSocialCore.h>
#import "EMCDDeviceManager.h" //环信
#import "WXApi.h"
#import "AdvertisingViewController.h"
#import "PYWLaunchTool.h" //统一的启动工具
#import "LoginViewController.h"

@interface AppDelegate ()<JPUSHRegisterDelegate,EMChatManagerDelegate,WXApiDelegate>
{
    //没有内存管理的修饰符
    //成员变量 默认是strong
    BMKMapManager* _mapManager;
}

@property (nonatomic, strong) PYWLaunchTool *launchTool;

@end

@implementation AppDelegate

#pragma mark - 加载广告界面 （第一次本体广告）
- (void) loadAdverting
{
    NSString *imgUrlStr = [UserModel sharedInstanced].advertImg;
    AdvertisingViewController *vc = [AdvertisingViewController new];
    NSInteger timeInt = [UserModel sharedInstanced].advertTimeInt;
    // 跳过回调方法
    vc.getAdvertisingBack = ^{
        CATransition *animation = [CATransition animation];
        animation.type = kCATransitionFade;
        [self.window.layer addAnimation:animation forKey:nil];
        
        HomePageViewController *vc = [[HomePageViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = nav;
    };
    if (imgUrlStr.length > 0 && ![imgUrlStr  isEqual: @""]) {// 加载上一次网络 请求的广告
        vc.a = timeInt;
        [vc.titleImageView sd_setImageWithURL:[NSURL URLWithString:imgUrlStr]];
    }else{ // 第一次请求本地的广告
        vc.a = 15;
        vc.titleImageView.image = [UIImage imageNamed:@"StartPage1125"];
    }
    self.window.rootViewController  = vc;
    [self.window makeKeyAndVisible];
}



/////////
- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
    
}

- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx071a16ef2a9e5d5d" appSecret:@"537ce0df34dcf0af9ba42a782a275002" redirectURL:nil];
    
}
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    [WXApi handleOpenURL:url delegate:self];
    return result;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    [WXApi handleOpenURL:url delegate:self];
    return result;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    [WXApi handleOpenURL:url delegate:self];
    return result;
}


#pragma mark 跳转处理
////被废弃的方法. 但是在低版本中会用到.建议写上
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return [WXApi handleOpenURL:url delegate:self];
//}
//被废弃的方法. 但是在低版本中会用到.建议写上

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    return [WXApi handleOpenURL:url delegate:self];
//}

////新的方法
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
//{
//    return [WXApi handleOpenURL:url delegate:self];
//}

-(void) onResp:(BaseResp*)resp
{
    switch (resp.errCode) {
        case WXSuccess:
            NSLog(@"%@",@"支付结果：成功！");
            NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"wxpayBackOver" object:nil];// 微信支付成功跳转界面通知（这个控制器
            break;
        default:
            NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
            break;
    }
}
// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}
//在线普通消息会走以下回调：(环信)
/*!
 @method
 @brief 接收到一条及以上非cmd消息
 */
- (void)messagesDidReceive:(NSArray *)aMessages
{
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
    
}
- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    return result;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UMSocialManager defaultManager] openLog:YES];
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"59755f6ab27b0a2bb600223d"];
    /* 微信聊天 */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx071a16ef2a9e5d5d" appSecret:@"537ce0df34dcf0af9ba42a782a275002" redirectURL:@"http://mobile.umeng.com/social"];
    
    [self.launchTool startRunning];
    
    //AppKey:注册的AppKey，环信
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:@"1125180704177188#chatdemo-ui"];
    options.apnsCertName = @"chatdemo-ui";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    NSString *telephoneStr = [UserModel sharedInstanced].mobile;
    EMError *error2 = [[EMClient sharedClient] loginWithUsername:telephoneStr password:telephoneStr];
    if (!error2) {
        NSLog(@"登录成功");
        [[EMClient sharedClient].options setIsAutoLogin:YES];// 自动登录
    }
    // 后台注册
    //    EMError *error = [[EMClient sharedClient] registerWithUsername:@"8001" password:@"111111"];
    //    if (error==nil) {
    //        NSLog(@"注册成功");
    //    }
    
//        EMError *error2 = [[EMClient sharedClient] loginWithUsername:@"15940070932" password:@"15940070932"];
//        if (!error2) {
//            NSLog(@"登录成功");
//            [[EMClient sharedClient].options setIsAutoLogin:YES];// 自动登录
//        }
    //注册消息回调
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    
    // UMConfigure 通用设置，请参考SDKs集成做统一初始化。
    // 以下仅列出U-Share初始化部分
    // U-Share 平台设置
    [self configUSharePlatforms];
    [self confitUShareSettings];
    
    //向微信注册wx5b034ee2d273be73
    [WXApi registerApp:@"wx071a16ef2a9e5d5d"];
    
    if (launchOptions) { //是否有推送消息
        NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]; //这是判断app是否是由远程通知启动的   若是由本地通知启动的 则把 UIApplicationLaunchOptionsRemoteNotificationKey 换成 UIApplicationLaunchOptionsLocalNotificationKey
        
        if (remoteNotification) { //是否有远程推送消息
            //            [self jumpToViewctroller:remoteNotification]; //这是跳转页面的方法。
        }
    }
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    
#warning 一定要记得修改bundleID
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"ahPaG95jk1CilQXZrxUGGTWrLBisqEfR"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //    NSString *userid = [UserModel sharedInstanced].userId;
    //实例化
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#warning 广告
    NSString *kADImgurlString = [[NSUserDefaults standardUserDefaults] objectForKey:kADImgurl];
    NSInteger timeInt = [UserModel sharedInstanced].advertTimeInt;
    if (kADImgurlString.length) {
        AdvertisingViewController *vc = [AdvertisingViewController new];
        [vc.titleImageView sd_setImageWithURL:[NSURL URLWithString:kADImgurlString]];
        vc.a = timeInt;
        // 跳过回调方法
        vc.getAdvertisingBack = ^{
            CATransition *animation = [CATransition animation];
            animation.type = kCATransitionFade;
            [self.window.layer addAnimation:animation forKey:nil];
            
            HomePageViewController *vc = [[HomePageViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
            self.window.rootViewController = nav;
        };
        self.window.rootViewController  = vc;
    } else {
        CATransition *animation = [CATransition animation];
        animation.type = kCATransitionFade;
        [self.window.layer addAnimation:animation forKey:nil];
        
        HomePageViewController *vc = [[HomePageViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = nav;
    }
    [self.window makeKeyAndVisible];
    
    //背景颜色
    //    self.window.backgroundColor = [UIColor whiteColor];
    
    //设置app属性
    [self setupAppStyle];
    
    /**
     极光推送代码
     */
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"07bae642d15f6e8b2b2facea"
                          channel:@"App Store"
                 apsForProduction:0
            advertisingIdentifier:advertisingId];
    
    
    // 注册通知  账号在其他设备登录时 接收极光自定义消息 （极光后台 在自定义消息 发送时候）
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    
    /**已上是极光推送*/
    
    /**讯飞语音识别*/
    //Set log level
    [IFlySetting setLogFile:LVL_ALL];
    //Set whether to output log messages in Xcode console
    [IFlySetting showLogcat:YES];
    //Set the local storage path of SDK
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    //Set APPID
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"5b2c61ef"];
    //Configure and initialize iflytek services.(This interface must been invoked in application:didFinishLaunchingWithOptions:)
    [IFlySpeechUtility createUtility:initString];
    return YES;
}

//设置app属性
- (void)setupAppStyle{
    //修改状态栏颜色 + plist文件
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    //设置nav title颜色
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    [UINavigationBar appearance].titleTextAttributes = attributes;
    //设置nav背景颜色
    [UINavigationBar appearance].barTintColor = getColor(mainColor);
    //设置tab title颜色
    [UITabBar appearance].tintColor = getColor(mainColor);
    [UINavigationBar appearance].tintColor = [UIColor whiteColor];
    
    //设置背景颜色
    [UITabBar appearance].barTintColor = [UIColor whiteColor];
    // 去掉TabBar上边的线
    //    [[UITabBar appearance] setTranslucent:NO];
    //    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    //    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
}

// 首页
- (void)loginStateChange
{
    self.window.rootViewController = nil;
    HomePageViewController *homePageViewController = [[HomePageViewController alloc]init];
    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:homePageViewController];
    self.window.rootViewController = navVc;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark- 以下是极光代码
/**
 极光推送 回调
 */

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
//    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    // 这个block回调获取registrationID 别名 存储起来 在登录界面传给后台
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0)
        {
            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
//            NSLog(@"registrationID获取成功：%@",registrationID);
//            [UserModel sharedInstanced].jpushRegistrationID = registrationID;
//            [self.launchTool jspushRegisterToServers:registrationID]; // 登陆后上传设备别名给后台
        }
        else
        {
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    completionHandler(UNNotificationPresentationOptionSound);
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        HomePageViewController *homePageViewController = [[HomePageViewController alloc]init];
        homePageViewController.isJpush = YES;
        NSString *stra = userInfo[@"state"];
        homePageViewController.stateStr = userInfo[@"state"];
        UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:homePageViewController];
        self.window.rootViewController = navVc;
        [self.window makeKeyAndVisible];
    }
    completionHandler();  // 系统要求执行这个方法
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; //清除角标
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"];                 // 推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];    // badge数量
    NSString *sound = [aps valueForKey:@"sound"];                   // 播放的声音
    
    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"];  // 服务端中Extras字段，key是自己定义的
    NSLog(@"\nAppDelegate:\ncontent =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
// 接收到通知事件  （自定义消息）
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段，key是自己定义的
    
//    [self setRootViewControllWithLoginVC];
}
// 退出登录
- (void)setRootViewControllWithLoginVC{
    [UserModel sharedInstanced].userId = @"";
    [UserModel sharedInstanced].headImg = @"";
    [UserModel sharedInstanced].nameNick = @"";
    EMError *error = [[EMClient sharedClient] logout:YES]; //环信退出登录
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:loginVC];
    [self.window setRootViewController:navc];
    //    ShowMessage(@"您的账号已在其他设备登录，请重新登录！");
    
    
    
    [self.window makeToast:@"您的账号已在其他设备登录，请重新登录！" duration:1 position:CSToastPositionCenter];
    return;
}
- (PYWLaunchTool *)launchTool{
    if (!_launchTool) {
        _launchTool = [[PYWLaunchTool alloc]init];
    }
    return _launchTool;
}

@end

